package com.suisung.shopsuite.account.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suisung.shopsuite.account.model.entity.UserAttestation;
import com.suisung.shopsuite.account.model.req.UserAttestationReq;
import com.suisung.shopsuite.account.repository.UserAttestationRepository;
import com.suisung.shopsuite.account.service.UserAttestationService;
import com.suisung.shopsuite.common.utils.CheckUtil;
import com.suisung.shopsuite.core.web.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserAttestationServiceImpl extends BaseServiceImpl<UserAttestationRepository, UserAttestation, UserAttestationReq> implements UserAttestationService {

    @Resource
    private UserAttestationRepository userAttestationRepository;

    @Override
    public boolean saveUserAttestation(UserAttestation userAttestation){
        if (userAttestation.getUdIsDefault() != null && userAttestation.getUdIsDefault()){
            QueryWrapper<UserAttestation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userAttestation.getUserId());
            queryWrapper.eq("ud_is_default",true);

            if (CheckUtil.isNotEmpty(userAttestation.getAttestationId())){
                queryWrapper.ne("attestation_id",userAttestation.getAttestationId());
            }

            List<UserAttestation> userAttestationList = find(queryWrapper);

            if (CollectionUtil.isNotEmpty(userAttestationList)) {
                userAttestationList.forEach(item -> item.setUdIsDefault(false));
                userAttestationRepository.saveOrUpdate(userAttestationList);
            }
        }
        return save(userAttestation);
    }
}
